import React, {useEffect, useState} from 'react'
import {
	Button,
	Space,
	Modal,
	Row,
	Col,
	Form,
	Input,
	Select,
	Table,
	Pagination,
} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {connect} from 'umi'
import {ExclamationCircleFilled} from '@ant-design/icons'
import moment from 'moment'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import {
	getList,
	editConfiguraion,
	creatConfiguration,
} from '@/service/configuration/index'
import Permissions from '@/components/Permissions'

interface DataType {
	id: string | string[] | null
	statusStr: string
	businessTypeStr: string
	expenseItemTypeStr: string
	expenseItemName: string
	createTime: string
	status: number
}
const formItemLayout = {
	labelCol: {flex: '100px'},
	wrapperCol: {flex: '1'},
}

const admittance = () => {
	const [dataSourse, setDataSourse] = useState([])
	const [loading, setLoading] = useState<boolean>(false)
	const [total, setTotal] = useState()
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [formData, setFormData] = useState<any[]>([])
	const [form] = Form.useForm()
	// 搜索条件
	const [formValue, setFormValue] = useState({})
	const [searchData, setSearchData] = useState({})
	// 获取供列表
	const getData = () => {
		getList({...params, ...searchData}).then((res: any) => {
			if (res.success) {
				setLoading(false)
				setTotal(res?.data?.total)
				setDataSourse(res?.data?.records)
			}
		})
	}
	useEffect(() => {
		getData()
	}, [params])
	// 清空
	const onReset = () => {
		setSearchData(()=>{})
		const param = {
			current: 1,
			size: params.size,
		}
		setParams(() => param)
		getData()
	}
	/** 停用启用 */
	const onDetails = (type: string, record: DataType) => {
		const config = {
			title: '提示',
			icon: <ExclamationCircleFilled />,
			content:
				type === '2'
					? '确认要启用此条费用项吗？'
					: '确认要停用此条费用项吗？',
			onOk() {
				const status = type === '2' ? 2 : 1
				editConfiguraion({id: record?.id, status})
					.then((res: any) => {
						if (res.success) {
							getData()
							form.resetFields()
							setFormValue({
								businessType: '',
								status: '',
								expenseItemType: '',
								expenseItemName: '',
								createTime: '',
							})
						}
					})
					.catch(() => {})
			},
			onCancel() {},
		}
		Modal.confirm(config)
	}
	// 新增修改弹窗
	const [isModalOpen, setIsModalOpen] = useState(false)

	const columns: ColumnsType<DataType> = [
		{
			title: '编号',
			dataIndex: 'id',
			align: 'center',
			width: 120,
			key: 'id',
			render(text, record, index) {
				return <span>{(params.current - 1) * 10 + index + 1}</span>
			},
		},
		{
			title: '状态',
			dataIndex: 'statusStr',
			align: 'center',
			width: 120,
			key: 'statusStr',
		},
		{
			title: '业务类型',
			dataIndex: 'businessTypeStr',
			align: 'center',
			width: 160,
			key: 'businessTypeStr',
		},
		{
			title: '费用项类型',
			dataIndex: 'expenseItemTypeStr',
			align: 'center',
			width: 120,
			key: 'expenseItemTypeStr',
		},
		{
			title: '费用项名称',
			dataIndex: 'expenseItemName',
			align: 'center',
			width: 100,
			key: 'expenseItemName',
		},
		{
			title: '创建时间',
			dataIndex: 'createTime',
			align: 'center',
			width: 180,
			key: 'createTime',
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 120,
			render: (text: any, record) => (
				<Space size={12}>
					{record?.status === 2 ? (
						<Button
							type="link"
							onClick={() => {
								onDetails('1', record)
							}}>
							停用
						</Button>
					) : (
						<Button
							type="link"
							onClick={() => {
								onDetails('2', record)
							}}>
							启用
						</Button>
					)}
				</Space>
			),
		},
	]
	useEffect(() => {
		const formItems: any[] = [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'select',
						label: '状态',
						name: 'status',
						key: 'status',
						items: [
							{
								value: 2,
								label: '启用',
							},
							{
								value: 1,
								label: '停用',
							},
						],
						span: 7,
					},
					{
						type: 'select',
						label: '业务类型',
						name: 'businessType',
						key: 'businessType',
						items: [
							{
								value: 1,
								label: '退车',
							},
							{
								value: 2,
								label: '换车',
							},
							{
								value: 3,
								label: '过户',
							},
							{
								value: 4,
								label: '调拨',
							},
						],
						span: 7,
					},
					{
						type: 'select',
						label: '费用项类型',
						name: 'expenseItemType',
						key: 'expenseItemType',
						items: [
							{
								value: 1,
								label: '扣款费用项',
							},
							{
								value: 2,
								label: '减免费用项',
							},
							{
								value: 3,
								label: '其他',
							},
						],
						span: 7,
					},
					{
						type: 'input',
						label: '费用项目名',
						name: 'expenseItemName',
						key: 'expenseItemName',
						span: 7,
					},
					{
						type: 'dateRange',
						label: '创建时间',
						placeholder: '创建时间范围',
						name: 'createTime',
						key: 'createTime',
						subtype: 'date',
						span: 7,
					},
				],
			},
		]
		setFormData(formItems)
	}, [])
	// 页码改变触发
	const paginationChange = (current: number, size: number) => {
		setParams({current, size})
	}
	//  搜索
	const onFinish = (values: any) => {
		let startTime: string = ''
		let endTime: string = ''
		if (values?.createTime) {
			startTime = moment(values?.createTime[0]).format(
				'YYYY-MM-DD HH:mm:ss',
			)
			endTime = moment(values?.createTime[1]).format(
				'YYYY-MM-DD HH:mm:ss',
			)
		}
		const start1 = startTime.split(' ')[0]
		const end1 = endTime.split(' ')[0]

		const info: any = {
			startTime: values?.createTime ? `${start1} 00:00:00` : '',
			endTime: values?.createTime ? `${end1} 23:59:59` : '',
			status: values?.status || '',
			businessType: values?.businessType || '',
			expenseItemType: values?.expenseItemType || '',
			expenseItemName: values?.expenseItemName || '',
		}
		setSearchData(() => info)
		const param = {
			current: 1,
			size: params.size,
		}
		setParams(() => param)
	}

	// 按钮列表
	const btnList = [
		{
			text: '新增',
			type: 'primary',
			id: 'amc_order_add',
			onClick: () => {
				form.resetFields()
				setIsModalOpen(() => true)
			},
		},
	]
	// 新增确定
	const onSubmit = async () => {
		const formDatas = await form.validateFields()
		const data: any = {
			expenseItemName: formDatas?.expenseItemName?.trim(),
			businessType: formDatas?.businessType,
			expenseItemType: formDatas?.expenseItemType,
		}
		creatConfiguration(data).then((res) => {
			if (res.success) {
				setIsModalOpen(() => false)
				getData()
			}
		})
	}
	// 新增取消
	const onCancel = () => {
		form.resetFields()
		setIsModalOpen(() => false)
	}

	return (
		<div className={styles.admittance}>
			<div className={styles.content}>
				<div className={styles.search}>
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formData}
						formLayout={formItemLayout}
						values={formValue}
					/>
				</div>
				<div className={styles.btnList}>
					{btnList.map((item: any) => (
						<Permissions permissionID="amc_basic_data">
							<Button {...item} ghost size="small" type="primary">
								{item.text}
							</Button>
						</Permissions>
					))}
				</div>
				<Table
					columns={columns}
					rowKey="id"
					bordered
					dataSource={dataSourse}
					loading={loading}
					pagination={false}
				/>
				<div className={styles.pagination}>
					<Pagination
						defaultCurrent={1}
						current={params.current}
						total={total}
						showTotal={(totals, range) =>
							`第  ${range[0]} - ${range[1]} 条 / 总共 ${totals} 条`
						}
						showSizeChanger
						showQuickJumper
						onChange={paginationChange}
					/>
				</div>
				<Modal
					title="新增费用项"
					open={isModalOpen}
					onOk={onSubmit}
					onCancel={onCancel}
					width="40%"
					destroyOnClose
					footer={
						<>
							<Button onClick={onCancel}>取消</Button>
							<Button
								type="primary"
								size="small"
								onClick={onSubmit}>
								保存
							</Button>
						</>
					}>
					<Form
						form={form}
						name="basic"
						layout="horizontal"
						labelCol={{flex: '120px'}}
						labelAlign="right"
						labelWrap
						initialValues={{remember: true}}
						autoComplete="off">
						<Row gutter={10}>
							<Col
								sm={{span: 24}}
								md={{span: 24}}
								lg={{span: 24}}>
								<Form.Item
									label="费用项目名称"
									name="expenseItemName"
									rules={[{required: true}]}>
									<Input placeholder="请输入" />
								</Form.Item>
							</Col>

							<Col
								sm={{span: 24}}
								md={{span: 24}}
								lg={{span: 24}}>
								<Form.Item
									label="业务类型"
									name="businessType"
									rules={[{required: true}]}>
									<Select
										placeholder="请选择"
										options={[
											{
												value: 1,
												label: '退车',
											},
											{
												value: 2,
												label: '换车',
											},
											{
												value: 3,
												label: '过户',
											},
											{
												value: 4,
												label: '调拨',
											},
										]}
									/>
								</Form.Item>
							</Col>
							<Col
								sm={{span: 24}}
								md={{span: 24}}
								lg={{span: 24}}>
								<Form.Item
									label="费用项类型"
									name="expenseItemType"
									rules={[{required: true}]}>
									<Select
										placeholder="请选择"
										options={[
											{
												value: 1,
												label: '扣款费用项',
											},
											{
												value: 2,
												label: '减免费用项',
											},
											{
												value: 3,
												label: '其他',
											},
										]}
									/>
								</Form.Item>
							</Col>
						</Row>
					</Form>
				</Modal>
			</div>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(admittance)
